<?php
//namespace student\controller\welcome;
defined('BASEPATH') OR exit('No direct script access allowed');

class Upload extends CI_Controller {


	public function __construct()
	{
		parent::__construct();
		$this->load->helper('url_helper');
		date_default_timezone_set('Asia/Shanghai');
		session_start();
	}

    /**
    *  上传文件函数分发
    */
	public function index()
	{
		$file_type = @$_REQUEST['file_type'];
		
		$if_show = @$_REQUEST['if_show'];
       
		/*if($if_show == 'false'){
			var_dump($_FILES);
			var_dump($_REQUEST);
			exit;
		}*/


		if($file_type == 'pic'){
			$this->uploadPic($if_show);
		} else {

			print json_encode(array('desc'=>'未定义上传的类型'));
		}
		
	}

	/**
	**  上传图片处理函数
	**/
	public function uploadPic($if_show=true)
	{
		if($if_show == "false"){ //表示不进行页面展示，而是进行处理
			$targetFolder = '/bigdataforphp/picture/user/';
			if (!empty($_FILES)) {
			    $file_name = iconv("UTF-8","gb2312", $_FILES['file']['name']); //文件名称
			    $filenames= explode(".",$file_name);
			    $tempFile = $_FILES['file']['tmp_name'];
			    $pic_name = $_SESSION['user_id'];
			    $targetPath = $_SERVER['DOCUMENT_ROOT'] . '/' .ltrim($targetFolder,'/'); //图片存放目录
			    $targetFile = rtrim($targetPath,'/') . '/' .$pic_name.".".$filenames[count($filenames)-1]; //图片完整路徑

			    // Validate the file type
			    $fileTypes = array('jpg', 'jpeg', 'png'); // File extensions
			    $fileParts = pathinfo($_FILES['file']['name']);

			    if (in_array($fileParts['extension'],$fileTypes)) {
			        move_uploaded_file($tempFile,iconv("UTF-8","gb2312", $targetFile));
					print json_encode(array("code"=>0,"desc"=>"图片上传成功",'state'=>'SUCCESS',"url"=>base_url()."picture/user/".$pic_name.".".$filenames[count($filenames)-1]));
			        //exit(json_encode(array("url"=>$targetFile,'name'=>$file_name)));
			    } else {
			        echo '非法的图片格式';
			    }
			}
		} else {
            $this->load->view("home/uploadPic");
		}
		
	}


}
